import requests
import json
from datetime import datetime
import socket

class WeatherAPI:
    def __init__(self):
        self.jwt_token = "eyJhbGciOiJFZERTQSIsImtpZCI6IlRDQjVXUUE1Uk4ifQ.eyJzdWIiOiIyNkU1RkM4Q1g2IiwiaWF0IjoxNzUyODg1MTkxLCJleHAiOjE3NTI4ODYwOTF9.xx_u-_X3OwaFrs8D5ZZxV-YGqR0LqqRSb4THoLnC9Sm8UJ4ctuxBfTHBn_53mMX6LIO8jg6plA7hEDv8F0TJDA"
        self.api_host = "ph2yvvkn2q.re.qweatherapi.com"
        self.base_url = f"https://{self.api_host}/v7/warning/now"
        self.location_id = "101090601"

    def get_weather_warnings(self):
        """获取天气预警信息（使用JWT认证）"""
        headers = {
            "Authorization": f"Bearer {self.jwt_token}",
            "Accept-Encoding": "gzip",
        }
        params = {"location": self.location_id, "lang": "zh"}

        try:
            # 测试域名解析
            try:
                socket.gethostbyname(self.api_host)
            except socket.gaierror:
                return {
                    "status": "error",
                    "message": f"域名解析失败: {self.api_host}",
                    "data": [],  # 确保返回空列表
                    "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                }

            # 明确禁用代理
            proxies = {
                "http": None,
                "https": None,
            }
            
            # 发送请求
            response = requests.get(
                self.base_url,
                headers=headers,
                params=params,
                timeout=10,
                proxies=proxies
            )
            
            # 添加调试信息
            print(f"API响应状态码: {response.status_code}")
            
            response.raise_for_status()
            data = response.json()
            
            # 确保返回标准化的数据结构
            return {
                "status": "success",
                "code": data.get("code", "200"),
                "data": data.get("warning", []),  # 确保总是返回列表
                "updateTime": data.get("updateTime", datetime.now().isoformat()),
                "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }

        except requests.exceptions.RequestException as e:
            print(f"请求异常: {str(e)}")
            return {
                "status": "error",
                "message": str(e),
                "data": [],  # 确保返回空列表
                "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }

    def check_extreme_weather(self):
        """检查是否有极端天气（供定时任务使用）"""
        result = self.get_weather_warnings()
        if result['status'] == 'success' and result['data']:
            # 检查是否有严重预警
            severe_warnings = [
                w for w in result['data'] 
                if w.get('severity') in ['Severe', 'Extreme', 'Red']
            ]
            if severe_warnings:
                return {
                    "status": "extreme",
                    "warnings": severe_warnings
                }
        return {"status": "normal"}

# 示例用法
if __name__ == "__main__":
    api = WeatherAPI()
    result = api.get_weather_warnings()
    print(json.dumps(result, indent=2, ensure_ascii=False))